# chat/models.py
from django.db import models
from django.utils import timezone
import uuid
from django.conf import settings
from django.dispatch import receiver
from django.db.models.signals import post_save
from django.utils.translation import gettext_lazy as _

# 导入你的自定义用户模型
from accounts.models import Student, Teacher


# 会话模型
class Conversation(models.Model):
    """表示两个用户之间的聊天会话"""
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        ordering = ['-updated_at']


# 会话参与者中间表
class ConversationParticipant(models.Model):
    USER_TYPE = (
        ('student', '学生'),
        ('teacher', '教师'),
    )

    conversation = models.ForeignKey(Conversation, on_delete=models.CASCADE)
    student = models.ForeignKey(Student, on_delete=models.CASCADE, null=True, blank=True)
    teacher = models.ForeignKey(Teacher, on_delete=models.CASCADE, null=True, blank=True)
    user_type = models.CharField(max_length=10, choices=USER_TYPE)
    unread_messages = models.IntegerField(default=0)
    last_read_at = models.DateTimeField(null=True, blank=True)
    is_blocked = models.BooleanField(default=False)

    class Meta:
        unique_together = ('conversation', 'student', 'teacher')

    def get_user(self):
        """获取参与者的用户对象"""
        if self.user_type == 'student':
            return self.student
        return self.teacher

    def __str__(self):
        user = self.get_user()
        return f"{user} in {self.conversation}"


# 消息模型
class Message(models.Model):
    """聊天消息"""
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    conversation = models.ForeignKey(Conversation, on_delete=models.CASCADE, related_name='messages')
    sender_student = models.ForeignKey(Student, on_delete=models.CASCADE, null=True, blank=True)
    sender_teacher = models.ForeignKey(Teacher, on_delete=models.CASCADE, null=True, blank=True)
    content = models.TextField()
    is_read = models.BooleanField(default=False)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        ordering = ['created_at']

    def get_sender(self):
        """获取消息发送者的用户对象"""
        if self.sender_student:
            return self.sender_student
        return self.sender_teacher

    def __str__(self):
        sender = self.get_sender()
        return f"消息: {sender} -> {self.conversation} ({self.created_at})"


# 用户在线状态跟踪
class UserStatus(models.Model):
    USER_TYPE = (
        ('student', '学生'),
        ('teacher', '教师'),
    )

    student = models.OneToOneField(Student, on_delete=models.CASCADE, null=True, blank=True)
    teacher = models.OneToOneField(Teacher, on_delete=models.CASCADE, null=True, blank=True)
    user_type = models.CharField(max_length=10, choices=USER_TYPE)
    is_online = models.BooleanField(default=False)
    last_seen = models.DateTimeField(default=timezone.now)

    def get_user(self):
        """获取用户对象"""
        if self.user_type == 'student':
            return self.student
        return self.teacher

    def __str__(self):
        # 避免在__str__中执行数据库查询
        user_id = self.student_id if self.user_type == 'student' else self.teacher_id
        return f"用户ID={user_id}的状态: {'在线' if self.is_online else '离线'}"


# 信号处理器，自动为新用户创建UserStatus
@receiver(post_save, sender=Student)
def create_student_status(sender, instance, created, **kwargs):
    if created:
        UserStatus.objects.create(student=instance, user_type='student')


@receiver(post_save, sender=Teacher)
def create_teacher_status(sender, instance, created, **kwargs):
    if created:
        UserStatus.objects.create(teacher=instance, user_type='teacher')